package com.reins.bookstore.utils.filesutils;

import com.reins.bookstore.entity.UserAuth;

import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class FileUtils {
    public static final String BOOK_DATA = "book_data.json";
    public static final String BASKET_LINE_DATA = "basket_line_data.json";
    public static final String ORDER_ITEM_DATA = "order_item_data.json";
    public static final String ORDERS_DATA = "orders_data.json";
    public static final String USER_DATA = "user_data.json";
    public static final String USER_AUTH_DATA = "user_auth_data.json";
    public static final String BASE_DIR = "./document/";

    public static String readJsonFile(String fileName) {
        String jsonStr;
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8);
            int ch = 0;
            StringBuilder sb = new StringBuilder();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void writeJsonFile(String object, String fileName){
        try{
            BufferedWriter out = new BufferedWriter(new FileWriter(BASE_DIR + fileName));
            out.write(object);
            out.close();
        } catch (IOException e){
            e.printStackTrace();
        }
    }
    public static JSONArray get_books(){
        String  read_get = readJsonFile(BASE_DIR+BOOK_DATA);
        JSONArray result =  JSONArray.fromObject(read_get);
        return result;
    }
    public static JSONArray get_basket_lines(){
        String  read_get = readJsonFile(BASE_DIR+BASKET_LINE_DATA);
        JSONArray result =  JSONArray.fromObject(read_get);
        return result;
    }
    public static JSONArray get_order_items(){
        String  read_get = readJsonFile(BASE_DIR+ORDER_ITEM_DATA);
        JSONArray result =  JSONArray.fromObject(read_get);
        return result;
    }
    public static JSONArray get_orders(){
        String  read_get = readJsonFile(BASE_DIR+ORDERS_DATA);
        JSONArray result =  JSONArray.fromObject(read_get);
        return result;
    }
    public static JSONArray get_users(){
        String  read_get = readJsonFile(BASE_DIR+USER_DATA);
        JSONArray result =  JSONArray.fromObject(read_get);
        return result;
    }
    public static JSONArray get_user_auth(){
        String  read_get = readJsonFile(BASE_DIR+ USER_AUTH_DATA);
        JSONArray result =  JSONArray.fromObject(read_get);
        return result;
    }
}
